import akshare as ak
import json
import os,sys
import pandas as pd
import datetime

dir_path = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.join(dir_path, '..'))

from common import utils

now = datetime.datetime.now()
month = now.month
year = now.year
print("当前:", year, month)

lrb_map_file = '/usr/share/nginx/html/888/lrb.json'
lrb_date_file = '/usr/share/nginx/html/888/lrb-date.json'
reportPoint = ['0331', '0630', '0930', '1231']

def getReportNode(year, index):
    if index < 0:
        i = index + 4
        y = year - 1
    else:
        i = index
        y = year

    return y, i, "%d%s" % (y, reportPoint[int(i)])
    
def load(day):
    try:
        path = "/tmp/lrb_%s.csv" % (day)
        if (not os.path.exists(path)):
            print("update ", path)
            lrb = ak.stock_lrb_em(date=day)
            if (datetime.datetime.now() - datetime.datetime.strptime(day, '%Y%m%d')).days < 62:
                # 因为最近这次财报可能没有公布完全，部分企业还没有公布，最大延迟2个月，这期间不能缓存到csv，以便每次拉取最新
                print("use online ", day)
                lrb.to_csv("/tmp/lrb_cache_%s.csv" % (utils.cur_day()))
                return lrb

            lrb.to_csv(path)

        print("cache ", path)
        return pd.read_csv(path, dtype={'股票代码':str})
    except Exception as err:
        print("not found report of ", day, ',err=', err)
        return None


report_year, report_index, report_point = getReportNode(year, int((month-1)/3 - 1))
yjyg_df = ak.stock_yjyg_em(date=report_point)
yjyg_df.to_csv("/tmp/yjyg_cache_%s.csv" % (utils.cur_day()))

latest_df = load(report_point)
if latest_df is None:
    report_year, report_index, report_point = getReportNode(report_year, report_index-1)
    latest_df = load(report_point)

prev_df = load("%d%s" % (report_year-1, reportPoint[report_index]))

print('当期%d支，上期%d支' % (len(latest_df), len(prev_df)))

found = {}
found_date = {}
prev_jlr = {}

# 去年同期净利润
for index, row in prev_df.iterrows():
    code = row['股票代码']
    name = row['股票简称']
    if utils.isBadStock(code, name):
        continue

    prev_jlr[code] = {
        "jlr": int(row['净利润'])
    }

# 当前净利润
for index, row in latest_df.iterrows():
    code = row['股票代码']
    name = row['股票简称']
    date = row['公告日期']
    if utils.isBadStock(code, name):
        continue
       
    if (code not in prev_jlr):
        continue

    jlr = int(row['净利润'])
    pre = prev_jlr[code]['jlr']
    if (jlr > 0 and pre < 0):
        # 同期利润又负变正，视为扭亏为盈
        found[code] = '%s->%s(%s正式)' % (utils.formatNumber(pre), utils.formatNumber(jlr), date)

        date = str(date)
        if date not in found_date:
            found_date[date] = []
        found_date[date].append({
            "code": code,
            "name": name,
            "detail": '%s->%s(正式)' % (utils.formatNumber(pre), utils.formatNumber(jlr))
        })

# 业绩预告
for index, row in yjyg_df.iterrows():
    code = row['股票代码']
    name = row['股票简称']
    yczb = row['预测指标']
    ycsz = row['预测数值']
    yglx = row['预告类型']
    ggrq = row['公告日期']
    tqz = row['上年同期值']
    if utils.isBadStock(code, name):
        continue
    
    if '净利润' in yczb and yglx == '扭亏' and  (code not in found):
        found[code] = '%s->%s(%s预告)' % (utils.formatNumber(tqz), utils.formatNumber(ycsz), ggrq)

        date = str(ggrq)
        if date not in found_date:
            found_date[date] = []
        found_date[date].append({
            "code": code,
            "name": name,
            "detail": '%s->%s(预告)' % (utils.formatNumber(tqz), utils.formatNumber(ycsz))
        })

with open(lrb_map_file, 'w') as f:
    json.dump(found, f, ensure_ascii=False)

with open(lrb_date_file, 'w') as f:
    json.dump(found_date, f, ensure_ascii=False)
